<?php if (!defined('BASEPATH')) exit('No direct script access allowed');

class Api extends MY_Controller
{
    /** @var \User */
    private $CurrentUser;

    public function __construct()
    {
        parent::__construct();

        // 检查状态
        YimeDevTools::checkSiteStatus();

        $this->CurrentUser = UserManager::getCurrentUserBySession();
        if (!$this->input->is_ajax_request()) {
            //todo 不是ajax请求
        }
    }

    public function register($bind_type = false)
    {
        try {
            $registerName = $this->input->get_post('register_name');
            $registerPassword = $this->input->get_post('register_password');
            $registerCaptcha = $this->input->get_post('register_captcha');

            if ($registerName === false || $registerPassword === false || $registerCaptcha === false) {
                throw new ParaException('参数不齐');
            }

            if (strlen($registerName) < 3 || strlen($registerName) > 30) {
                throw new FormatException('账号长度不正确');
            }

            if (strlen($registerPassword) < 6 || strlen($registerPassword) > 30) {
                throw new FormatException('密码长度不正确');
            }

            if (!Captcha_Model::isWordExist($registerCaptcha)) {
                throw new NotMatchException('验证码不正确');
            }

            $thatUser = UserManager::register($registerName, $registerPassword);

            $this->load->helper('string');
            $activationCode = random_string('alnum', 10);

            UserActivation_Model::update($thatUser->getId(), $activationCode);

            $YimeEmail = new YimeEmail;
            $sendMailResult = $YimeEmail->sendMailRegisterSuccess($registerName, $activationCode);

            $thatUser = UserManager::login($registerName, $registerPassword);

            if (!$sendMailResult)
                throw new SendEmailFailedException('注册邮件发送失败，请联系管理员');

            Captcha_Model::isWordExistAndDeleteItSelfByWord($registerCaptcha);

            if ($sendMailResult) {
                preg_match_all('/(\w)+((\.\w{2,3}){1,3})$/', $registerName, $mailurl);
                $mail_weburl = "http://mail." . $mailurl['0']['0'];
                if (strpos($mail_weburl, 'mail.gmail.com') !== FALSE) {
                    $mail_weburl = 'http://mail.google.com'; //特判gmail
                    return;
                }
                if ($bind_type == false) {
                    echo json_encode(array(
                        'type' => 'success',
                        'message' => '邮件发送成功^_^',
                        'mail_url' => $mail_weburl,
                        'data' => $thatUser->getDataArray(),
                    ));
                } elseif ($bind_type == 'weibo') {
                    $result = WeiboManger::bindWeibo();
                    if ($result) {
                        echo json_encode(array(
                            'type' => 'success',
                            'message' => '注册成功，并成功绑定微博，激活邮件已发送，现在去激活？',
                            'mail_url' => $mail_weburl,
                        ));
                    } elseif ($result == 'addWeiboInfo_fail') {
                        echo json_encode(array(
                            'type' => 'fail',
                            'message' => '获取微博信息失败，请重试！',
                        ));
                    } else {
                        echo json_encode(array(
                            'type' => 'fail',
                            'message' => '添加微博信息失败，请重试！',
                        ));
                    }
                }
            } else {
                echo json_encode(array(
                    'type' => 'fail',
                    'message' => '邮件发送失败，请联系管理员！',
                    'data' => $thatUser->getDataArray(),
                ));
            }

        } catch (NotExistException $e) {
            echo json_encode(array(
                'type' => 'warning',
                'message' => $e->getMessage(),
            ));
        } catch (AlreadyExistException $e) {
            echo json_encode(array(
                'type' => 'warning',
                'message' => $e->getMessage(),
            ));
        } catch (NotMatchException $e) {
            echo json_encode(array(
                'type' => 'warning',
                'message' => $e->getMessage(),
            ));
        } catch (FormatException $e) {
            echo json_encode(array(
                'type' => 'warning',
                'message' => $e->getMessage(),
            ));
        } catch (ParaException $e) {
            echo json_encode(array(
                'type' => 'error',
                'message' => $e->getMessage(),
            ));
        } catch (DatabaseException $e) {
            echo json_encode(array(
                'type' => 'error',
                'message' => $e->getMessage(),
            ));
        } catch (Exception $e) {
            echo json_encode(array(
                'type' => 'error',
                'message' => $e->getMessage(),
            ));
        }
    }

    public function resendActivationEmail()
    {
        try {
            $userId = $this->input->get_post('user_id');
            $thatUser = User_Model::getUserById($userId);

            //检查是否获取成功
            if (!$thatUser || $thatUser->getID() == 0)
                throw new NotExistException('UserID不存在');

            //检查权限
            if ($thatUser->getId() != $this->CurrentUser->getId() && !$this->CurrentUser->isAdministrator())
                throw new PermissionDeniedException('无权重发该用户激活邮件');

            //检查是否已激活过
            if ($thatUser->getPower() > 0)
                throw new Exception('账号已处于激活状态');

            $this->load->helper('string');
            $activationCode = random_string('alnum', 10);

            UserActivation_Model::update($thatUser->getId(), $activationCode);

            $YimeEmail = new YimeEmail;
            $sendMailResult = $YimeEmail->sendMailRegisterSuccess($thatUser->getEmail(), $activationCode);

            if (!$sendMailResult)
                throw new SendEmailFailedException('邮件发送失败，请联系管理员');

            echo json_encode(array(
                'type' => 'success',
                'message' => '发送成功，请接收验证邮件并激活账号',
                'data' => $thatUser->getDataArray(),
            ));
        } catch (NotExistException $e) {
            echo json_encode(array(
                'type' => 'warning',
                'message' => $e->getMessage(),
            ));
        } catch (AlreadyExistException $e) {
            echo json_encode(array(
                'type' => 'warning',
                'message' => $e->getMessage(),
            ));
        } catch (NotMatchException $e) {
            echo json_encode(array(
                'type' => 'warning',
                'message' => $e->getMessage(),
            ));
        } catch (FormatException $e) {
            echo json_encode(array(
                'type' => 'warning',
                'message' => $e->getMessage(),
            ));
        } catch (Exception $e) {
            echo json_encode(array(
                'type' => 'error',
                'message' => $e->getMessage(),
            ));
        }
    }

    public function activation()
    {
        try {
            $activationCode = $this->input->get_post('activation_code');

            if ($activationCode === false) {
                throw new ParaException('参数不齐');
            }

            $thatUser = User_Model::getUserById(UserActivation_Model::getUserIdAndDeleteItSelfByActivationCode($activationCode));

            if (!$thatUser) {
                throw new NotExistException('链接不存在或已过期');
            }

            if ($thatUser->getPower() > 0)
                throw new Exception('账号已处于激活状态');

            $thatUser->setPower(1);

            $thatUser = User_Model::update($thatUser);

            echo json_encode(array(
                'type' => 'success',
                'message' => '成功激活',
                'data' => $thatUser->getDataArray(),
            ));
        } catch (NotExistException $e) {
            echo json_encode(array(
                'type' => 'warning',
                'message' => $e->getMessage(),
            ));
        } catch (Exception $e) {
            echo json_encode(array(
                'type' => 'error',
                'message' => $e->getMessage(),
            ));
        }
    }

    public function login()
    {
        try {
            $loginName = $this->input->get_post('login_name');
            $loginPassword = $this->input->get_post('login_password');

            echo json_encode(array(
                'type' => 'test',
                'username'=>$loginName,
                'password'=>$loginPassword
            ));
            die();
            if ($loginName === false || $loginPassword === false) {
                throw new ParaException('参数不齐');
            }

            if (strlen($loginName) < 3 || strlen($loginName) > 30) {
                throw new FormatException('账号长度不正确');
            }

            if (strlen($loginPassword) < 6) {
                throw new FormatException('密码长度不正确');
            }

            $thatUser = UserManager::login($loginName, $loginPassword);

            $login_type = $this->session->userdata('bindType');
            if ($login_type === 'weibo') {
                echo json_encode(array(
                    'type' => 'alert',
                    'message' => '登录成功',
                    'data' => $login_type,
                ));
            } else {
                echo json_encode(array(
                    'type' => 'success',
                    'message' => '登录成功',
                    'data' => $thatUser->getDataArray(),
                ));
            }
        } catch (NotExistException $e) {
            echo json_encode(array(
                'type' => 'warning',
                'message' => $e->getMessage(),
            ));
        } catch (NotMatchException $e) {
            echo json_encode(array(
                'type' => 'warning',
                'message' => $e->getMessage(),
            ));
        } catch (AlreadyExistException $e) {
            echo json_encode(array(
                'type' => 'warning',
                'message' => $e->getMessage(),
            ));
        } catch (FormatException $e) {
            echo json_encode(array(
                'type' => 'warning',
                'message' => $e->getMessage(),
            ));
        } catch (ParaException $e) {
            echo json_encode(array(
                'type' => 'error',
                'message' => $e->getMessage(),
            ));
        } catch (DatabaseException $e) {
            echo json_encode(array(
                'type' => 'error',
                'message' => $e->getMessage(),
            ));
        } catch (Exception $e) {
            echo json_encode(array(
                'type' => 'error',
                'message' => $e->getMessage(),
            ));
        }
    }

    public function logout()
    {
        UserManager::logout();
    }

    public function show_guide()
    {
        delete_cookie('visited');
        redirect(base_url());
    }

    public function addSchool()
    {
        try {
            //检查权限
            if (!$this->CurrentUser->isAdministrator())
                throw new PermissionDeniedException('无权添加学校信息');

            $schoolName = $this->input->get_post('school_name');
            $schoolCountry = $this->input->get_post('school_country');
            $schoolProvince = $this->input->get_post('school_province');
            $schoolCity = $this->input->get_post('school_city');
            $schoolRegion = $this->input->get_post('school_region');
            $schoolAddress = $this->input->get_post('school_address');

            $thatSchool = new School();

            if (!$schoolName)
                throw new FormatException('学校名称不能为空');

            $thatSchool->setName($schoolName);
            $thatSchool->setCountry($schoolCountry);
            $thatSchool->setProvince($schoolProvince);
            $thatSchool->setCity($schoolCity);
            $thatSchool->setRegion($schoolRegion);
            $thatSchool->setAddress($schoolAddress);

            $thatSchool = School_Model::add($thatSchool);

            echo json_encode(array(
                'type' => 'success',
                'message' => '添加成功',
                'data' => $thatSchool->getDataArray(),
            ));
        } catch (NotExistException $e) {
            echo json_encode(array(
                'type' => 'warning',
                'message' => $e->getMessage(),
            ));
        } catch (NotMatchException $e) {
            echo json_encode(array(
                'type' => 'warning',
                'message' => $e->getMessage(),
            ));
        } catch (AlreadyExistException $e) {
            echo json_encode(array(
                'type' => 'warning',
                'message' => $e->getMessage(),
            ));
        } catch (FormatException $e) {
            echo json_encode(array(
                'type' => 'warning',
                'message' => $e->getMessage(),
            ));
        } catch (Exception $e) {
            echo json_encode(array(
                'type' => 'error',
                'message' => $e->getMessage(),
            ));
        }
    }

    public function  feedback()
    {
        $feedback_content = $this->input->get_post('feedback-content');
        $feedback = new feedback();
        $feedback->setReleaseTime(date("Y-m-d H:i:s", time()));
        $feedback->setContent($feedback_content);
        $feedback_result = feedback_Model::add($feedback);
        if ($feedback_result) {
            echo json_encode(array(
                'type' => 'success',
                'message' => '发布成功',
            ));
        }
    }

    public function studentRealNameAuth()
    {
        try {
            $userId = $this->input->get_post('user_id');
            $thatUser = User_Model::getUserById($userId);

            $schoolId = $this->input->get_post('school_id');
            $thatSchool = School_Model::getSchoolById($schoolId);

            //检查是否获取成功
            if (!$thatUser || $thatUser->getID() == 0)
                throw new NotExistException('UserID不存在');

            if (!$thatSchool || $thatSchool->getID() == 0)
                throw new NotExistException('SchoolID不存在');

            //检查权限
            if ($thatUser->getId() != $this->CurrentUser->getId() && !$this->CurrentUser->isAdministrator())
                throw new PermissionDeniedException('无权进行该用户的实名认证');

            $studentNum = $this->input->get_post('student_num');
            $studentPwd = $this->input->get_post('student_pwd');
            $checkCode = $this->input->get_post('check_code');

            $thatStudentInfo = YimeRealNameAuth::doAuth($thatSchool->getAuthType(), array(
                'user_id' => $thatUser->getId(),
                'school_id' => $thatSchool->getId(),
                'student_num' => $studentNum,
                'student_pwd' => $studentPwd,
                'check_code' => $checkCode,
            ));
            if ($thatStudentInfo) {
                $thatUser->setStudentInfoId($thatStudentInfo->getId());
                $thatUser->setPower(2);
                $thatUser = User_Model::update($thatUser);

                $thatUserInfo = $thatUser->getUserInfo();
                $thatUserInfo->setRealName($thatStudentInfo->getStudentName());
                $thatUserInfo = UserInfo_Model::save($thatUserInfo);

                echo json_encode(array(
                    'type' => 'success',
                    'message' => '实名认证成功',
                    'data' => $thatStudentInfo->getDataArray(),
                ));
            } else {
                echo json_encode(array(
                    'type' => 'error',
                    'message' => '实名认证失败，请检测对应学校以及学号密码',
                ));
            }
        } catch (NotExistException $e) {
            echo json_encode(array(
                'type' => 'warning',
                'message' => $e->getMessage(),
            ));
        } catch (NotMatchException $e) {
            echo json_encode(array(
                'type' => 'warning',
                'message' => $e->getMessage(),
            ));
        } catch (AlreadyExistException $e) {
            echo json_encode(array(
                'type' => 'warning',
                'message' => $e->getMessage(),
            ));
        } catch (FormatException $e) {
            echo json_encode(array(
                'type' => 'warning',
                'message' => $e->getMessage(),
            ));
        } catch (Exception $e) {
            echo json_encode(array(
                'type' => 'error',
                'message' => $e->getMessage(),
            ));
        }
    }

    public function wantToSell()
    {
        try {
            $userId = $this->input->get_post('user_id');
            $thatUser = User_Model::getUserById($userId);

            //检查是否获取成功
            if (!$thatUser || $thatUser->getID() == 0)
                throw new NotExistException('UserID不存在');

            //检查权限
            if ($thatUser->getId() != $this->CurrentUser->getId() && !$this->CurrentUser->isAdministrator())
                throw new PermissionDeniedException('无权以该用户身份发布商品');

            $commodityTitle = $this->input->get_post('commodity_title');
            $releaseType = $this->input->get_post('release_type');
            $commodityCategory = $this->input->get_post('commodity_category');
            $commoditySubCategory = $this->input->get_post('commodity_sub_category');
            $commodityPrice = $this->input->get_post('commodity_price');
            $commodityStock = $this->input->get_post('commodity_stock');
            $commodityContactType = $this->input->get_post('commodity_contact_type');
            $commodityContactInfo = $this->input->get_post('commodity_contact_info');
            $commodityIntro = $this->input->get_post('commodity_intro');
            $commodityContent = $this->input->get_post('commodity_content');

            //判断物品分类是否选择有子项
            $commoditySubCategory_ = CommodityCategory_Model::getCommodityCategoryById($commoditySubCategory);
            $commoditySubCategory_fa = $commoditySubCategory_ ->getFatherId();
            $commodityCat = $commoditySubCategory_fa == $commodityCategory ? $commoditySubCategory : $commodityCategory;

            $thatCommodity = new Commodity();
            if (!$commodityTitle)
                throw new FormatException('标题不能为空');
            if (!$commodityIntro)
                throw new FormatException('简介不能为空');
            if (!is_numeric($commodityPrice))
                throw new NotMatchException('价格只需填写数字');
            if (!is_numeric($commodityContactInfo))
                throw new NotMatchException('填写正确的联系号码');
            if (mb_strlen($commodityIntro, 'UTF-8') > 180)
                throw new NotMatchException('字数超过180');
            $thatCommodity->setTitle($commodityTitle);

            $thatCommodity->setCommodityCatId($commodityCat);

            $thatCommodity->setReleaseType($releaseType);
            $thatCommodity->setReleaseTime(date("Y-m-d H:i:s", time()));

            $thatCommodity->setPrice($commodityPrice);
            $thatCommodity->setStock($commodityStock);

            $thatCommodity->setContactType($commodityContactType);
            $thatCommodity->setContactInfo($commodityContactInfo);

            $thatCommodity->setIntro($commodityIntro);

            if($commodityContent == ""){
                $commodityContent=$commodityIntro;
             }
            $commodityContent=YimeTools::sanitize_html($commodityContent);

            $thatCommodity->setContent($commodityContent);
            $thatCommodity->setUserId($this->CurrentUser->getId());

            $thatCommodity->setImageHash($thatCommodity->getDisplayImageHash());

            //发到用户的学校
            $user_school_unicode = $this->CurrentUser->getStudentInfo()->getSchool()->getUnicode();
            $thatCommodity->setSchoolunicode($user_school_unicode);

            $thatCommodity = Commodity_Model::add($thatCommodity);

            echo json_encode(array(
                'type' => 'success',
                'message' => '发布成功',
                'data' => $thatCommodity->getDataArray(),
            ));
        } catch (NotExistException $e) {
            echo json_encode(array(
                'type' => 'warning',
                'message' => $e->getMessage(),
            ));
        } catch (NotMatchException $e) {
            echo json_encode(array(
                'type' => 'warning',
                'message' => $e->getMessage(),
            ));
        } catch (AlreadyExistException $e) {
            echo json_encode(array(
                'type' => 'warning',
                'message' => $e->getMessage(),
            ));
        } catch (FormatException $e) {
            echo json_encode(array(
                'type' => 'warning',
                'message' => $e->getMessage(),
            ));
        } catch (ParaException $e) {
            echo json_encode(array(
                'type' => 'error',
                'message' => $e->getMessage(),
            ));
        } catch (DatabaseException $e) {
            echo json_encode(array(
                'type' => 'error',
                'message' => $e->getMessage(),
            ));
        } catch (Exception $e) {
            echo json_encode(array(
                'type' => 'error',
                'message' => $e->getMessage(),
            ));
        }
    }

    public function wantToBuy()
    {
        try {
            $userId = $this->input->get_post('user_id');
            $thatUser = User_Model::getUserById($userId);

            //检查是否获取成功
            if (!$thatUser || $thatUser->getID() == 0)
                throw new NotExistException('UserID不存在');

            //检查权限
            if ($thatUser->getId() != $this->CurrentUser->getId() && !$this->CurrentUser->isAdministrator())
                throw new PermissionDeniedException('无权以该用户身份发布求购');

            $title = $this->input->get_post('commodity_require_title');
            $minPrice = $this->input->get_post('commodity_require_min_price');
            $maxPrice = $this->input->get_post('commodity_require_max_price');
            $category = $this->input->get_post('commodity_require_category');
            $num = $this->input->get_post('commodity_require_num');
            $content = $this->input->get_post('commodity_require_content');
            $commodityContactType = $this->input->get_post('commodity_contact_type');
            $commodityContactInfo = $this->input->get_post('commodity_contact_info');
            $release_type = $this->input->get_post('release-type'); //1 求物 2 求人 3 求帮

            if (!$title)
                throw new FormatException('标题不能为空');
            if (!$content)
                throw new FormatException('描述不能为空');
            if (!is_numeric($minPrice) || !is_numeric($maxPrice))
                throw new FormatException('价格只需填写数字');
            if (!is_numeric($commodityContactInfo))
                throw new NotMatchException('填写正确的联系号码');
            if (!is_numeric($num))
                throw new FormatException('物品数量只需填写数字');
            if (mb_strlen($content, 'UTF-8') > 180)
                throw new NotMatchException('字数超过180');
            $thatCommodityRequire = new CommodityRequire;
            $thatCommodityRequire->setTitle($title);
            $thatCommodityRequire->setMinPrice($minPrice);
            $thatCommodityRequire->setMaxPrice($maxPrice);
            $thatCommodityRequire->setContactType($commodityContactType);
            $thatCommodityRequire->setContactInfo($commodityContactInfo);
            $thatCommodityRequire->setCommodityCatId($category);
            $thatCommodityRequire->setNum($num);

            $thatCommodityRequire->setReleaseType($release_type);
            $thatCommodityRequire->setReleaseTime(date("Y-m-d H:i:s", time()));

            $thatCommodityRequire->setContent($content);

            $thatCommodityRequire->setUserId($thatUser->getId());
            //发到用户的学校
            $user_school_unicode = $this->CurrentUser->getStudentInfo()->getSchool()->getUnicode();
            $thatCommodityRequire->setSchoolunicode($user_school_unicode);

            $thatCommodityRequire = CommodityRequire_Model::add($thatCommodityRequire);

            echo json_encode(array(
                'type' => 'success',
                'message' => '发布成功',
                'data' => $thatCommodityRequire->getDataArray(),
            ));
        } catch (NotExistException $e) {
            echo json_encode(array(
                'type' => 'warning',
                'message' => $e->getMessage(),
            ));
        } catch (NotMatchException $e) {
            echo json_encode(array(
                'type' => 'warning',
                'message' => $e->getMessage(),
            ));
        } catch (AlreadyExistException $e) {
            echo json_encode(array(
                'type' => 'warning',
                'message' => $e->getMessage(),
            ));
        } catch (FormatException $e) {
            echo json_encode(array(
                'type' => 'warning',
                'message' => $e->getMessage(),
            ));
        } catch (ParaException $e) {
            echo json_encode(array(
                'type' => 'error',
                'message' => $e->getMessage(),
            ));
        } catch (DatabaseException $e) {
            echo json_encode(array(
                'type' => 'error',
                'message' => $e->getMessage(),
            ));
        } catch (Exception $e) {
            echo json_encode(array(
                'type' => 'error',
                'message' => $e->getMessage(),
            ));
        }
    }

    public function editCommodity()
    {
        try {
            $commodityId = $this->input->get_post('commodity_id');
            $thatCommodity = Commodity_Model::getCommodityById($commodityId);
            $thatUser = $thatCommodity->getUser();

            //检查是否获取成功
            if (!$thatUser || $thatUser->getID() == 0)
                throw new NotExistException('UserID不存在');

            //检查权限
            if ($thatUser->getId() != $this->CurrentUser->getId() && !$this->CurrentUser->isAdministrator())
                throw new PermissionDeniedException('无权以该用户身份发布商品');

            $commodityTitle = $this->input->get_post('commodity_title');
            $releaseType = $this->input->get_post('release_type');
            $commodityCategory = $this->input->get_post('commodity_category');
            $commoditySubCategory = $this->input->get_post('commodity_sub_category');
            $commodityPrice = $this->input->get_post('commodity_price');
            $commodityStock = $this->input->get_post('commodity_stock');
            $commodityContactInfo = $this->input->get_post('commodity_contact_info');
            $commodityContactType = $this->input->get_post('commodity_contact_type');
            $commodityIntro = $this->input->get_post('commodity_intro');
            $commodityContent = $this->input->get_post('commodity_content');

            //判断物品分类是否选择有子项
            $commoditySubCategory_ = CommodityCategory_Model::getCommodityCategoryById($commoditySubCategory);
            $commoditySubCategory_fa = $commoditySubCategory_ ->getFatherId();
            $commodityCat = $commoditySubCategory_fa == $commodityCategory ? $commoditySubCategory : $commodityCategory;

            if (!$commodityTitle)
                throw new FormatException('标题不能为空');
            if (!$commodityIntro)
                throw new FormatException('简介不能为空');

            $thatCommodity->setTitle($commodityTitle);

            $thatCommodity->setCommodityCatId($commodityCat);

            $thatCommodity->setContactType($commodityContactType);
            $thatCommodity->setContactInfo($commodityContactInfo);

            $thatCommodity->setReleaseType($releaseType);
            $thatCommodity->setReleaseTime(date("Y-m-d H:i:s", time()));

            $thatCommodity->setPrice($commodityPrice);
            $thatCommodity->setStock($commodityStock);

            $thatCommodity->setIntro($commodityIntro);
            $thatCommodity->setContent($commodityContent);

            $thatCommodity->setUserId($thatUser->getId());

            $thatCommodity = Commodity_Model::update($thatCommodity);

            echo json_encode(array(
                'type' => 'success',
                'message' => '修改成功',
                'data' => $thatCommodity->getDataArray(),
            ));
        } catch (NotExistException $e) {
            echo json_encode(array(
                'type' => 'warning',
                'message' => $e->getMessage(),
            ));
        } catch (NotMatchException $e) {
            echo json_encode(array(
                'type' => 'warning',
                'message' => $e->getMessage(),
            ));
        } catch (AlreadyExistException $e) {
            echo json_encode(array(
                'type' => 'warning',
                'message' => $e->getMessage(),
            ));
        } catch (FormatException $e) {
            echo json_encode(array(
                'type' => 'warning',
                'message' => $e->getMessage(),
            ));
        } catch (ParaException $e) {
            echo json_encode(array(
                'type' => 'error',
                'message' => $e->getMessage(),
            ));
        } catch (DatabaseException $e) {
            echo json_encode(array(
                'type' => 'error',
                'message' => $e->getMessage(),
            ));
        } catch (Exception $e) {
            echo json_encode(array(
                'type' => 'error',
                'message' => $e->getMessage(),
            ));
        }
    }

    public function editRequire()
    {
        try {
            $commodityRequireId = $this->input->get_post('commodityrequire_id');
            $thatRequire = CommodityRequire_Model::getCommodityRequireById($commodityRequireId);
            $thatUser = $thatRequire->getUser();

            //检查是否获取成功
            if (!$thatUser || $thatUser->getID() == 0)
                throw new NotExistException('UserID不存在');

            //检查权限
            if ($thatUser->getId() != $this->CurrentUser->getId() && !$this->CurrentUser->isAdministrator())
                throw new PermissionDeniedException('无权以该用户身份发布商品');

            $commodityTitle = $this->input->get_post('commodity_require_title');
            $MinPrice = $this->input->get_post('commodity_require_min_price');
            $MaxPrice = $this->input->get_post('commodity_require_max_price');
            $commodityCategory = $this->input->get_post('commodity_require_category');
            $commodityNum = $this->input->get_post('commodity_require_num');
            $requireContact = $this->input->get_post('commodity_require_content');
            $release_type = $this->input->get_post('release-type'); //1 求物 2 求人 3 求帮


            if (!$commodityTitle)
                throw new FormatException('标题不能为空');

            $thatRequire->setTitle($commodityTitle);

            $thatRequire->setCommodityCatId($commodityCategory);

            $thatRequire->setMinPrice($MinPrice);
            $thatRequire->setMaxPrice($MaxPrice);

            $thatRequire->setNum($commodityNum);
            $thatRequire->setContent($requireContact);

            $thatRequire->setUserId($thatUser->getId());
            $thatRequire->setReleaseType($release_type);

            $thatRequire = CommodityRequire_Model::update($thatRequire);

            echo json_encode(array(
                'type' => 'success',
                'message' => '修改成功',
                'data' => $thatRequire->getDataArray(),
            ));
        } catch (NotExistException $e) {
            echo json_encode(array(
                'type' => 'warning',
                'message' => $e->getMessage(),
            ));
        } catch (NotMatchException $e) {
            echo json_encode(array(
                'type' => 'warning',
                'message' => $e->getMessage(),
            ));
        } catch (AlreadyExistException $e) {
            echo json_encode(array(
                'type' => 'warning',
                'message' => $e->getMessage(),
            ));
        } catch (FormatException $e) {
            echo json_encode(array(
                'type' => 'warning',
                'message' => $e->getMessage(),
            ));
        } catch (ParaException $e) {
            echo json_encode(array(
                'type' => 'error',
                'message' => $e->getMessage(),
            ));
        } catch (DatabaseException $e) {
            echo json_encode(array(
                'type' => 'error',
                'message' => $e->getMessage(),
            ));
        } catch (Exception $e) {
            echo json_encode(array(
                'type' => 'error',
                'message' => $e->getMessage(),
            ));
        }
    }

    public function deleteCommodity()
    {
        try {
            $commodityId = $this->input->get_post('commodity_id');
            $thatCommodity = Commodity_Model::getCommodityById($commodityId);
            $thatUser = $thatCommodity->getUser();

            //检查是否获取成功
            if (!$thatUser || $thatUser->getID() == 0)
                throw new NotExistException('UserID不存在');

            //检查权限
            if ($thatUser->getId() != $this->CurrentUser->getId() && !$this->CurrentUser->isAdministrator())
                throw new PermissionDeniedException('无权删除该商品');

            Commodity_Model::delete($thatCommodity);

            echo json_encode(array(
                'type' => 'success',
                'message' => '删除成功',
            ));
        } catch (NotExistException $e) {
            echo json_encode(array(
                'type' => 'warning',
                'message' => $e->getMessage(),
            ));
        } catch (NotMatchException $e) {
            echo json_encode(array(
                'type' => 'warning',
                'message' => $e->getMessage(),
            ));
        } catch (AlreadyExistException $e) {
            echo json_encode(array(
                'type' => 'warning',
                'message' => $e->getMessage(),
            ));
        } catch (Exception $e) {
            echo json_encode(array(
                'type' => 'error',
                'message' => $e->getMessage(),
            ));
        }
    }

    public function deleteRequire()
    {
        try {
            $commodityRequireId = $this->input->get_post('commodity_id');
            $thatRequire = CommodityRequire_Model::getCommodityRequireById($commodityRequireId);
            $thatUser = $thatRequire->getUser();

            //检查是否获取成功
            if (!$thatUser || $thatUser->getID() == 0)
                throw new NotExistException('UserID不存在');

            //检查权限
            if ($thatUser->getId() != $this->CurrentUser->getId() && !$this->CurrentUser->isAdministrator())
                throw new PermissionDeniedException('无权删除该商品');

            CommodityRequire_Model::delete($thatRequire);

            echo json_encode(array(
                'type' => 'success',
                'message' => '删除成功',
            ));
        } catch (NotExistException $e) {
            echo json_encode(array(
                'type' => 'warning',
                'message' => $e->getMessage(),
            ));
        } catch (NotMatchException $e) {
            echo json_encode(array(
                'type' => 'warning',
                'message' => $e->getMessage(),
            ));
        } catch (AlreadyExistException $e) {
            echo json_encode(array(
                'type' => 'warning',
                'message' => $e->getMessage(),
            ));
        } catch (Exception $e) {
            echo json_encode(array(
                'type' => 'error',
                'message' => $e->getMessage(),
            ));
        }
    }

    public function deleteCommodityComment()
    {
        try {
            $commodityCommentId = $this->input->get_post('commodity_comment_id');
            $comment = CommodityComment_Model::getCommodityCommentById($commodityCommentId);
            $thatUser = $comment->getUser();

            //检查是否获取成功
            if (!$thatUser || $thatUser->getID() == 0)
                throw new NotExistException('UserID不存在');

            //检查权限
            if ($thatUser->getId() != $this->CurrentUser->getId() && !$this->CurrentUser->isAdministrator())
                throw new PermissionDeniedException('无权删除该评论');

            $comment->setDeletedFlag();
            CommodityComment_Model::update($comment);

            echo json_encode(array(
                'type' => 'success',
                'message' => '删除成功',
            ));
        } catch (NotExistException $e) {
            echo json_encode(array(
                'type' => 'warning',
                'message' => $e->getMessage(),
            ));
        } catch (NotMatchException $e) {
            echo json_encode(array(
                'type' => 'warning',
                'message' => $e->getMessage(),
            ));
        } catch (AlreadyExistException $e) {
            echo json_encode(array(
                'type' => 'warning',
                'message' => $e->getMessage(),
            ));
        } catch (Exception $e) {
            echo json_encode(array(
                'type' => 'error',
                'message' => $e->getMessage(),
            ));
        }
    }

    public function deleteCommodityRequireComment()
    {
        try {
            $commodityCommentId = $this->input->get_post('commodity_require_comment_id');
            $comment = CommodityRequireComment_Model::getCommodityRequireCommentById($commodityCommentId);
            $thatUser = $comment->getUser();

            //检查是否获取成功
            if (!$thatUser || $thatUser->getID() == 0)
                throw new NotExistException('UserID不存在');

            //检查权限
            if ($thatUser->getId() != $this->CurrentUser->getId() && !$this->CurrentUser->isAdministrator())
                throw new PermissionDeniedException('无权删除该评论');

            $comment->setDeletedFlag();
            CommodityRequireComment_Model::update($comment);

            echo json_encode(array(
                'type' => 'success',
                'message' => '删除成功',
            ));
        } catch (NotExistException $e) {
            echo json_encode(array(
                'type' => 'warning',
                'message' => $e->getMessage(),
            ));
        } catch (NotMatchException $e) {
            echo json_encode(array(
                'type' => 'warning',
                'message' => $e->getMessage(),
            ));
        } catch (AlreadyExistException $e) {
            echo json_encode(array(
                'type' => 'warning',
                'message' => $e->getMessage(),
            ));
        } catch (Exception $e) {
            echo json_encode(array(
                'type' => 'error',
                'message' => $e->getMessage(),
            ));
        }
    }

    public function setUserInfo()
    {
        try {
            $userId = $this->input->get_post('user_id');
            $thatUser = User_Model::getUserById($userId);

            //检查是否获取成功
            if (!$thatUser || $thatUser->getID() == 0)
                throw new NotExistException('UserID不存在');

            //检查权限
            if ($thatUser->getId() != $this->CurrentUser->getId() && !$this->CurrentUser->isAdministrator())
                throw new PermissionDeniedException('无权修改该用户资料');

            $nickName = $this->input->get_post('user_nick_name');
            $realName = $this->input->get_post('user_real_name');
            $sex = $this->input->get_post('user_sex');
            $qq = $this->input->get_post('user_qq');
            $phone = $this->input->get_post('user_phone');
            $phone_short = $this->input->get_post('user_phone_short');
            $contact_type = $this->input->get_post('user_contact_type');

            $prov = $this->input->get_post('prov');
            $city = $this->input->get_post('city');
            $dist = $this->input->get_post('dist');

            $profile = $this->input->get_post('user_profile');
            $birthday = $this->input->get_post('Ubirthday');

            $thatUserInfo = $thatUser->getUserInfo();

            if (!$thatUser->getStudentInfoId())
                $thatUserInfo->setRealName($realName);
            $thatUserInfo->setSex($sex);
            $thatUserInfo->setQq($qq);
            $thatUserInfo->setPhone($phone);
            $thatUserInfo->setPhoneShort($phone_short);
            $thatUserInfo->setProv($prov);
            $thatUserInfo->setCity($city);
            $thatUserInfo->setDist($dist);
            $thatUserInfo->setProfile($profile);
            $thatUserInfo->setUserId($userId);
            $thatUserInfo->setBirthday($birthday);
            $thatUserInfo->setDefaultContactType($contact_type);

            if ($thatUser->getUserInfoId()) {
                $thatUserInfo = UserInfo_Model::update($thatUserInfo);
            } else {
                $thatUserInfo = UserInfo_Model::add($thatUserInfo);
                $thatUser->setUserInfoId($thatUserInfo->getId());
                User_Model::update($thatUser);
            }
            $thatUser->setNickname($nickName);
            User_Model::update($thatUser);

            echo json_encode(array(
                'type' => 'success',
                'message' => '修改成功',
            ));
        } catch (NotMatchException $e) {
            echo json_encode(array(
                'type' => 'warning',
                'message' => $e->getMessage(),
            ));
        } catch (FormatException $e) {
            echo json_encode(array(
                'type' => 'warning',
                'message' => $e->getMessage(),
            ));
        } catch (DatabaseException $e) {
            echo json_encode(array(
                'type' => 'error',
                'message' => $e->getMessage(),
            ));
        } catch (Exception $e) {
            echo json_encode(array(
                'type' => 'error',
                'message' => $e->getMessage(),
            ));
        }
    }

    public function changeUserPassword()
    {
        $this->load->helper('security');
        try {
            $oldPassword = $this->input->get_post('now-password');
            $newPassword = $this->input->get_post('new-password');
            $userId = $this->session->userdata('UserID');
            $thatUser = User_Model::getUserById($userId);
            if ($thatUser->getPassword() !== do_hash(do_hash($oldPassword) . $thatUser->getSalt())) {
                echo json_encode(array(
                    'type' => 'error',
                    'message' => '原密码输入错误',
                ));
            } else {
                UserManager::changePassword($thatUser, $newPassword);
                echo json_encode(array(
                    'type' => 'success',
                    'message' => '修改密码成功，请重新登录！',
                    'data' => $thatUser->getUserInfo(),
                ));
            }
        } catch (NotExistException $e) {
            echo json_encode(array(
                'type' => 'warning',
                'message' => $e->getMessage(),
            ));
        } catch (NotMatchException $e) {
            echo json_encode(array(
                'type' => 'warning',
                'message' => $e->getMessage(),
            ));
        } catch (AlreadyExistException $e) {
            echo json_encode(array(
                'type' => 'warning',
                'message' => $e->getMessage(),
            ));
        } catch (FormatException $e) {
            echo json_encode(array(
                'type' => 'warning',
                'message' => $e->getMessage(),
            ));
        } catch (Exception $e) {
            echo json_encode(array(
                'type' => 'error',
                'message' => $e->getMessage(),
            ));
        }
    }

    public function setPwd_Token()
    {
        try {
            $userEmail = $this->input->get_post('email');
            $captcha = $this->input->get_post('verifycode');

            if ($userEmail === false || $captcha === false) {
                throw new ParaException('参数不齐');
            }
            if (!(Captcha_Model::isWordExist($captcha))) {
                echo json_encode(array(
                    'type' => 'error',
                    'message' => '验证码错误',
                ));
            } else {
                $this->load->helper('string');
                $thatUser = User_Model::getUserByEmail($userEmail);
                if ($thatUser) {
                    $resetPwd_Token = md5(time() . $userEmail . rand(0, 9999));
                    UserResetPwd_Model::update($thatUser->getId(), $resetPwd_Token);
                    $YimeEmail = new YimeEmail;
                    $sendMailResult = $YimeEmail->sendEmailResetPwd($userEmail, $resetPwd_Token);
                    if (!$sendMailResult)
                        throw new SendEmailFailedException('邮件发送失败，请联系管理员');

                    preg_match_all('/(\w)+((\.\w{2,3}){1,3})$/', $userEmail, $mailurl);
                    $mail_weburl = "http://mail." . $mailurl['0']['0'];
                    if (strpos($mail_weburl, 'mail.gmail.com') !== FALSE) {
                        $mail_weburl = 'http://mail.google.com'; //特判gmail
                    }
                    echo json_encode(array(
                        'type' => 'success',
                        'message' => '发送成功!',
                        'data' => $mail_weburl,
                    ));
                } else {
                    echo json_encode(array(
                        'type' => 'error',
                        'message' => '该邮箱未注册，请检查输入是否正确！',
                    ));
                }
            }
        } catch (NotExistException $e) {
            echo json_encode(array(
                'type' => 'warning',
                'message' => $e->getMessage(),
            ));
        } catch (Exception $e) {
            echo json_encode(array(
                'type' => 'error',
                'message' => $e->getMessage(),
            ));
        }
    }

    public function setnewpwd()
    {
        try {
            $newpwd = $this->input->get_post('newpwd');
            $email = $this->input->get_post('email');
            $resetpwd_token = $this->input->get_post('key');

            if ($newpwd === false || $email === false || $resetpwd_token === false) {
                throw new ParaException('参数不齐');
            }
            $thatUser = User_Model::getUserById(UserResetPwd_Model::getUserIdAndDeleteItSelfByResetPwdTokenCode($resetpwd_token));

            if ($thatUser !== null && $email === $thatUser->getEmail()) {
                UserManager::changePassword($thatUser, $newpwd);
                UserManager::login($email, $newpwd);
                echo json_encode(array(
                    'type' => 'success',
                    'message' => '密码设置成功！',
                ));
            } else {
                echo json_encode(array(
                    'type' => 'error',
                    'message' => '数据提交错误！',
                ));
            }

        } catch (NotMatchException $e) {
            echo json_encode(array(
                'type' => 'warning',
                'message' => $e->getMessage(),
            ));
        } catch (FormatException $e) {
            echo json_encode(array(
                'type' => 'warning',
                'message' => $e->getMessage(),
            ));
        } catch (DatabaseException $e) {
            echo json_encode(array(
                'type' => 'error',
                'message' => $e->getMessage(),
            ));
        } catch (Exception $e) {
            echo json_encode(array(
                'type' => 'error',
                'message' => $e->getMessage(),
            ));
        }
    }

    public function leaveCommodityComment()
    {
        try {
            $commodityId = $this->input->get_post('commodity_id');
            $fatherId = $this->input->get_post('father_id');
            $userId = $this->input->get_post('user_id');
            $content = $this->input->get_post('content');
            $private = $this->input->get_post('private') ? true : false;

            if (!$commodityId || !is_numeric($commodityId) || $commodityId <= 0 || !$content) {
                throw new ParaException('参数非法');
            }

            $commodity = Commodity_Model::getCommodityById($commodityId);
            if (!$commodity) {
                throw new NotExistException('该商品不存在');
            }

            if (!$userId || !is_numeric($userId)) {
                $userId = $this->CurrentUser->getId();
            }

            $thatUser = User_Model::getUserById($userId);

            //检查用户ID是否存在
            if (!$thatUser || $thatUser->getID() == 0)
                throw new NotExistException('UserID不存在');

            //检查权限
            if ($thatUser->getId() != $this->CurrentUser->getId() && !$this->CurrentUser->isAdministrator() && $thatUser->getPower() < 1)
                throw new PermissionDeniedException('无权以该用户身份发表留言');

            if (!$fatherId || !is_numeric($fatherId)) {
                $fatherId = 0;
            }
            $father = CommodityComment_Model::getCommodityCommentById($fatherId);

            $thatCommodityComment = new CommodityComment;
            $thatCommodityComment->setCommodityId($commodityId);
            $thatCommodityComment->setContent(htmlspecialchars($content));
            $thatCommodityComment->setFatherId($fatherId);
            $thatCommodityComment->setReleaseTime(date("Y-m-d H:i:s", time()));
            $thatCommodityComment->setPrivate($private);
            $thatCommodityComment->setUserId($userId);
            if ($father)
                $thatCommodityComment->setToUserId($father->getUserId());
            $thatCommodityComment->setMasterUserId($commodity->getUserId());

            $thatCommodityComment = CommodityComment_Model::add($thatCommodityComment);

            //更新新消息提醒
            $userNewMsg = UserNewMsg_Model::getUserNewMsgByUserId($commodity->getUserId());
            $userNewMsg->addCommentId($thatCommodityComment->getId());
            UserNewMsg_Model::save($userNewMsg);

            if ($father) {
                $userNewMsg = UserNewMsg_Model::getUserNewMsgByUserId($father->getUserId());
                $userNewMsg->addCommentId($thatCommodityComment->getId());
                UserNewMsg_Model::save($userNewMsg);
            }

            echo json_encode(array(
                'type' => 'success',
                'message' => '发表留言成功',
                'data' => $thatCommodityComment->getDataArray(),
            ));
        } catch (NotMatchException $e) {
            echo json_encode(array(
                'type' => 'warning',
                'message' => $e->getMessage(),
            ));
        } catch (FormatException $e) {
            echo json_encode(array(
                'type' => 'warning',
                'message' => $e->getMessage(),
            ));
        } catch (DatabaseException $e) {
            echo json_encode(array(
                'type' => 'error',
                'message' => $e->getMessage(),
            ));
        } catch (Exception $e) {
            echo json_encode(array(
                'type' => 'error',
                'message' => $e->getMessage(),
            ));
        }
    }

    public function leaveCommodityRequireComment()
    {
        try {
            $commodityRequireId = $this->input->get_post('commodity_require_id');
            $fatherId = $this->input->get_post('father_id');
            $userId = $this->input->get_post('user_id');
            $content = $this->input->get_post('content');
            $private = $this->input->get_post('private') ? true : false;

            if (!$commodityRequireId || !is_numeric($commodityRequireId) || $commodityRequireId <= 0 || !$content) {
                throw new ParaException('参数非法');
            }

            $commodityRequire = CommodityRequire_Model::getCommodityRequireById($commodityRequireId);
            if (!$commodityRequire) {
                throw new NotExistException('该求购不存在');
            }

            if (!$userId || !is_numeric($userId)) {
                $userId = $this->CurrentUser->getId();
            }

            $thatUser = User_Model::getUserById($userId);

            //检查用户ID是否存在
            if (!$thatUser || $thatUser->getID() == 0)
                throw new NotExistException('UserID不存在');

            //检查权限
            if ($thatUser->getId() != $this->CurrentUser->getId() && !$this->CurrentUser->isAdministrator() && $this->CurrentUser->getPower() < 1)
                throw new PermissionDeniedException('无权以该用户身份发表留言');

            if (!$fatherId || !is_numeric($fatherId)) {
                $fatherId = 0;
            }
            $father = CommodityRequireComment_Model::getCommodityRequireCommentById($fatherId);

            $thatCommodityRequireComment = new CommodityRequireComment;
            $thatCommodityRequireComment->setCommodityRequireId($commodityRequireId);
            $thatCommodityRequireComment->setContent(htmlspecialchars($content));
            $thatCommodityRequireComment->setFatherId($fatherId);
            $thatCommodityRequireComment->setReleaseTime(date("Y-m-d H:i:s", time()));
            $thatCommodityRequireComment->setPrivate($private);
            $thatCommodityRequireComment->setUserId($userId);
            if ($father)
                $thatCommodityRequireComment->setToUserId($father->getUserId());
            $thatCommodityRequireComment->setMasterUserId($commodityRequire->getUserId());

            $thatCommodityRequireComment = CommodityRequireComment_Model::add($thatCommodityRequireComment);

            //更新新消息提醒
            $userNewMsg = UserNewMsg_Model::getUserNewMsgByUserId($commodityRequire->getUserId());
            $userNewMsg->addCommentRequireId($thatCommodityRequireComment->getId());
            UserNewMsg_Model::save($userNewMsg);

            if ($father) {
                $userNewMsg = UserNewMsg_Model::getUserNewMsgByUserId($father->getUserId());
                $userNewMsg->addCommentRequireId($thatCommodityRequireComment->getId());
                UserNewMsg_Model::save($userNewMsg);
            }

            echo json_encode(array(
                'type' => 'success',
                'message' => '发表留言成功',
                'data' => $thatCommodityRequireComment->getDataArray(),
            ));
        } catch (NotMatchException $e) {
            echo json_encode(array(
                'type' => 'warning',
                'message' => $e->getMessage(),
            ));
        } catch (FormatException $e) {
            echo json_encode(array(
                'type' => 'warning',
                'message' => $e->getMessage(),
            ));
        } catch (DatabaseException $e) {
            echo json_encode(array(
                'type' => 'error',
                'message' => $e->getMessage(),
            ));
        } catch (Exception $e) {
            echo json_encode(array(
                'type' => 'error',
                'message' => $e->getMessage(),
            ));
        }
    }

    public function sellOutCommodity()
    {
        try {
            $commodityId = $this->input->get_post('commodity_id');
            $thatCommodity = Commodity_Model::getCommodityById($commodityId);
            $thatUser = $thatCommodity->getUser();

            //检查是否获取成功
            if (!$thatUser || $thatUser->getID() == 0)
                throw new NotExistException('UserID不存在');

            //检查权限
            if ($thatUser->getId() != $this->CurrentUser->getId() && !$this->CurrentUser->isAdministrator())
                throw new PermissionDeniedException('无权以该用户身份设置此商品');

            $thatCommodity->setStock(-$thatCommodity->getStock());

            $thatCommodity = Commodity_Model::update($thatCommodity);

            if ($thatCommodity->getStock() < 0)
                echo json_encode(array(
                    'type' => 'success',
                    'message' => '已设置售完标记',
                    'data' => $thatCommodity->getDataArray(),
                ));
            else {
                echo json_encode(array(
                    'type' => 'success',
                    'message' => '已取消售完标记',
                    'data' => $thatCommodity->getDataArray(),
                ));
            }
        } catch (NotExistException $e) {
            echo json_encode(array(
                'type' => 'warning',
                'message' => $e->getMessage(),
            ));
        } catch (NotMatchException $e) {
            echo json_encode(array(
                'type' => 'warning',
                'message' => $e->getMessage(),
            ));
        } catch (AlreadyExistException $e) {
            echo json_encode(array(
                'type' => 'warning',
                'message' => $e->getMessage(),
            ));
        } catch (FormatException $e) {
            echo json_encode(array(
                'type' => 'warning',
                'message' => $e->getMessage(),
            ));
        } catch (ParaException $e) {
            echo json_encode(array(
                'type' => 'error',
                'message' => $e->getMessage(),
            ));
        } catch (DatabaseException $e) {
            echo json_encode(array(
                'type' => 'error',
                'message' => $e->getMessage(),
            ));
        } catch (Exception $e) {
            echo json_encode(array(
                'type' => 'error',
                'message' => $e->getMessage(),
            ));
        }
    }

    public function putTopCommodity()
    {
        try {
            $commodityId = $this->input->get_post('commodity_id');
            $thatCommodity = Commodity_Model::getCommodityById($commodityId);
            $thatUser = $thatCommodity->getUser();

            //检查是否获取成功
            if (!$thatUser || $thatUser->getID() == 0)
                throw new NotExistException('UserID不存在');

            //检查权限
            if ($thatUser->getId() != $this->CurrentUser->getId() && !$this->CurrentUser->isAdministrator())
                throw new PermissionDeniedException('无权以该用户身份设置此商品');

            $array = Commodity_Model::getCommodityArrayByUserId($thatUser->getId(), false, false, 'release_time');
            foreach ($array as $thisCommodity) {
                /** @var Commodity $thisCommodity */
                if (strtotime($thisCommodity->getReleaseTime()) > time() - 7200)
                    throw new PermissionDeniedException('两小时内只能使用一次顶置哦');
            }

            $thatCommodity->setReleaseTime(date("Y-m-d H:i:s", time()));

            $thatCommodity = Commodity_Model::update($thatCommodity);

            echo json_encode(array(
                'type' => 'success',
                'message' => '顶置成功',
                'data' => $thatCommodity->getDataArray(),
            ));
        } catch (NotExistException $e) {
            echo json_encode(array(
                'type' => 'warning',
                'message' => $e->getMessage(),
            ));
        } catch (NotMatchException $e) {
            echo json_encode(array(
                'type' => 'warning',
                'message' => $e->getMessage(),
            ));
        } catch (PermissionDeniedException $e) {
            echo json_encode(array(
                'type' => 'warning',
                'message' => $e->getMessage(),
            ));
        } catch (FormatException $e) {
            echo json_encode(array(
                'type' => 'warning',
                'message' => $e->getMessage(),
            ));
        } catch (ParaException $e) {
            echo json_encode(array(
                'type' => 'error',
                'message' => $e->getMessage(),
            ));
        } catch (DatabaseException $e) {
            echo json_encode(array(
                'type' => 'error',
                'message' => $e->getMessage(),
            ));
        } catch (Exception $e) {
            echo json_encode(array(
                'type' => 'error',
                'message' => $e->getMessage(),
            ));
        }
    }

    public function getCommodityComment()
    {
        try {
            $userId = $this->input->get_post('user_id');
            $commodityId = $this->input->get_post('commodity_id');

            if (!$commodityId || !is_numeric($commodityId) || $commodityId <= 0) {
                throw new ParaException('参数非法');
            }

            if (!$userId || !is_numeric($userId)) {
                $userId = $this->CurrentUser->getId();
            }

            $thatUser = User_Model::getUserById($userId);

            //检查用户ID是否存在
            if (!$thatUser || $thatUser->getID() == 0)
                $thatUser = new User;

            //检查权限
            if ($thatUser->getId() != $this->CurrentUser->getId() && !$this->CurrentUser->isAdministrator())
                throw new PermissionDeniedException('无权以该用户身份获取留言');

            $thatCommodityCommentArray = CommodityComment_Model::getCommodityCommentArrayByCommodityId($commodityId, false, false, 'release_time');

            $data = array();
            foreach ($thatCommodityCommentArray as $thisCommodityComment) {
                /** @var CommodityComment $thisCommodityComment */
                //权限过滤
                if ($thisCommodityComment->isDeleted()) {
                    $data[] = $thisCommodityComment->getDataArrayAsDeleted();
                } else if ($thisCommodityComment->isPrivate()) {
                    if ($thatUser->getId() == $thisCommodityComment->getUserId() || $thatUser->getId() == $thisCommodityComment->getCommodityUserId() || $this->CurrentUser->isAdministrator())
                        $data[] = $thisCommodityComment->getDataArray();
                    else
                        $data[] = $thisCommodityComment->getDataArrayAsPrivate();
                } else {
                    $data[] = $thisCommodityComment->getDataArray();
                }
            }

            echo json_encode(array(
                'type' => 'success',
                'message' => '数据获取成功',
                'data' => $data,
            ));
        } catch (NotMatchException $e) {
            echo json_encode(array(
                'type' => 'warning',
                'message' => $e->getMessage(),
            ));
        } catch (FormatException $e) {
            echo json_encode(array(
                'type' => 'warning',
                'message' => $e->getMessage(),
            ));
        } catch (DatabaseException $e) {
            echo json_encode(array(
                'type' => 'error',
                'message' => $e->getMessage(),
            ));
        } catch (Exception $e) {
            echo json_encode(array(
                'type' => 'error',
                'message' => $e->getMessage(),
            ));
        }
    }

    public function getCommodityRequireComment()
    {
        try {
            $userId = $this->input->get_post('user_id');
            $commodityRequireId = $this->input->get_post('commodity_require_id');

            if (!$commodityRequireId || !is_numeric($commodityRequireId) || $commodityRequireId <= 0) {
                throw new ParaException('参数非法');
            }

            if (!$userId || !is_numeric($userId)) {
                $userId = $this->CurrentUser->getId();
            }

            $thatUser = User_Model::getUserById($userId);

            //检查用户ID是否存在
            if (!$thatUser || $thatUser->getID() == 0)
                $thatUser = new User;

            //检查权限
            if ($thatUser->getId() != $this->CurrentUser->getId() && !$this->CurrentUser->isAdministrator())
                throw new PermissionDeniedException('无权以该用户身份获取留言');

            $thatCommodityRequireCommentArray = CommodityRequireComment_Model::getCommodityRequireCommentArrayByCommodityRequireId($commodityRequireId, false, false, 'release_time');

            $data = array();
            foreach ($thatCommodityRequireCommentArray as $thisCommodityRequireComment) {
                /** @var CommodityRequireComment $thisCommodityRequireComment */
                //权限过滤
                if ($thisCommodityRequireComment->isDeleted()) {
                    $data[] = $thisCommodityRequireComment->getDataArrayAsDeleted();
                } else if ($thisCommodityRequireComment->isPrivate()) {
                    if ($thatUser->getId() == $thisCommodityRequireComment->getUserId() || $thatUser->getId() == $thisCommodityRequireComment->getCommodityRequireUserId() || $this->CurrentUser->isAdministrator())
                        $data[] = $thisCommodityRequireComment->getDataArray();
                    else
                        $data[] = $thisCommodityRequireComment->getDataArrayAsPrivate();
                } else {
                    $data[] = $thisCommodityRequireComment->getDataArray();
                }
            }

            echo json_encode(array(
                'type' => 'success',
                'message' => '数据获取成功',
                'data' => $data,
            ));
        } catch (NotMatchException $e) {
            echo json_encode(array(
                'type' => 'warning',
                'message' => $e->getMessage(),
            ));
        } catch (FormatException $e) {
            echo json_encode(array(
                'type' => 'warning',
                'message' => $e->getMessage(),
            ));
        } catch (DatabaseException $e) {
            echo json_encode(array(
                'type' => 'error',
                'message' => $e->getMessage(),
            ));
        } catch (Exception $e) {
            echo json_encode(array(
                'type' => 'error',
                'message' => $e->getMessage(),
            ));
        }
    }

    public function getCaptcha()
    {
        try {
            $this->load->helper('captcha');
            $data = array(
                'word' => random_string('alnum', 4),
                'img_path' => './public/captcha/',
                'img_url' => base_url('public/captcha') . '/',
                'font_path' => './public/font/arialbd.ttf',
                'img_width' => 160,
                'img_height' => 43,
            );
            $captcha = create_captcha($data);

            Captcha_Model::update($captcha);

            if (!$captcha || !$captcha['image'])
                $captcha = array('image' => '<p class="text-danger text-center" style="line-height: 40px;background: #fc8;">验证码生成出错</p>');

            echo json_encode(array(
                'type' => 'success',
                'message' => '数据获取成功',
                'data' => $captcha['image'],
            ));
        } catch (NotMatchException $e) {
            echo json_encode(array(
                'type' => 'warning',
                'message' => $e->getMessage(),
            ));
        } catch (FormatException $e) {
            echo json_encode(array(
                'type' => 'warning',
                'message' => $e->getMessage(),
            ));
        } catch (DatabaseException $e) {
            echo json_encode(array(
                'type' => 'error',
                'message' => $e->getMessage(),
            ));
        } catch (Exception $e) {
            echo json_encode(array(
                'type' => 'error',
                'message' => $e->getMessage(),
            ));
        }
    }

    public function commodityTogglePlusOne()
    {
        try {
            $commodityId = $this->input->get_post('commodity_id');
            $userId = $this->input->get_post('user_id');

            if (!$commodityId || !is_numeric($commodityId) || $commodityId <= 0) {
                throw new ParaException('参数非法');
            }

            if (!$userId || !is_numeric($userId)) {
                $userId = $this->CurrentUser->getId();
            }

            $thatUser = User_Model::getUserById($userId);

            //检查用户ID是否存在
            if (!$thatUser || $thatUser->getID() == 0)
                throw new NotExistException('NOTLOGIN');

            //检查权限
            if ($thatUser->getId() != $this->CurrentUser->getId() && !$this->CurrentUser->isAdministrator())
                throw new PermissionDeniedException('无权以该用户身份点赞');

            $thatCommodity = Commodity_Model::getCommodityById($commodityId);

            //检查商品ID是否存在
            if (!$thatCommodity || $thatCommodity->getID() == 0)
                throw new NotExistException('CommodityID不存在');

            $isCommodityPlusOneNow = CommodityPlusOne_Model::toggleCommodityPlusOne($thatCommodity->getId(), $thatUser->getId());

            echo json_encode(array(
                'type' => 'success',
                'message' => '点赞成功',
                'data' => array('isCommodityPlusOneNow' => $isCommodityPlusOneNow, 'countCommodityPlusOneNow' => CommodityPlusOne_Model::countCommodityPlusOneByCommodityId($thatCommodity->getId()),),
            ));
        } catch (NotMatchException $e) {
            echo json_encode(array(
                'type' => 'warning',
                'message' => $e->getMessage(),
            ));
        } catch (FormatException $e) {
            echo json_encode(array(
                'type' => 'warning',
                'message' => $e->getMessage(),
            ));
        } catch (DatabaseException $e) {
            echo json_encode(array(
                'type' => 'error',
                'message' => $e->getMessage(),
            ));
        } catch (Exception $e) {
            echo json_encode(array(
                'type' => 'error',
                'message' => $e->getMessage(),
            ));
        }
    }


    public function commodityToggleFavorite()
    {
        try {
            $commodityId = $this->input->get_post('commodity_id');
            $userId = $this->input->get_post('user_id');

            if (!$commodityId || !is_numeric($commodityId) || $commodityId <= 0) {
                throw new ParaException('参数非法');
            }

            if (!$userId || !is_numeric($userId)) {
                $userId = $this->CurrentUser->getId();
            }

            $thatUser = User_Model::getUserById($userId);

            //检查用户ID是否存在
            if (!$thatUser || $thatUser->getID() == 0)
                throw new NotExistException('NOTLOGIN');

            //检查权限
            if ($thatUser->getId() != $this->CurrentUser->getId() && !$this->CurrentUser->isAdministrator())
                throw new PermissionDeniedException('无权以该用户身份进行收藏');

            $thatCommodity = Commodity_Model::getCommodityById($commodityId);

            //检查商品ID是否存在
            if (!$thatCommodity || $thatCommodity->getID() == 0)
                throw new NotExistException('CommodityID不存在');

            $isCommodityInFavoriteNow = CommodityFavorite_Model::toggleCommodityFavorite($thatCommodity->getId(), $thatUser->getId());

            echo json_encode(array(
                'type' => 'success',
                'message' => '收藏成功',
                'data' => array('isCommodityInFavoriteNow' => $isCommodityInFavoriteNow,),
            ));
        } catch (NotMatchException $e) {
            echo json_encode(array(
                'type' => 'warning',
                'message' => $e->getMessage(),
            ));
        } catch (FormatException $e) {
            echo json_encode(array(
                'type' => 'warning',
                'message' => $e->getMessage(),
            ));
        } catch (DatabaseException $e) {
            echo json_encode(array(
                'type' => 'error',
                'message' => $e->getMessage(),
            ));
        } catch (Exception $e) {
            echo json_encode(array(
                'type' => 'error',
                'message' => $e->getMessage(),
            ));
        }
    }

    public function uploadFile()
    {
        try {
            if (!isset($_FILES["file"])) {
                throw new ParaException('参数非法');
            }
            $userId = $this->CurrentUser->getId();
            $thatUser = User_Model::getUserById($userId);

            //检查用户ID是否存在
            if (!$thatUser || $thatUser->getID() == 0)
                throw new NotExistException('非法用户');

            $fileUniName = strtolower($this->input->post('file_name'));
            $fileName = strtolower($this->input->post('file_ori_name'));
            $fileExt = strtolower('.' . end(explode('.', $fileName)));
            $fileUrl = $_FILES["file"]["tmp_name"];
            $chunk = $this->input->post('chunk');
            $chunks = $this->input->post('chunks');

            $thatFile = YimeUpload::uploadFile($userId, $fileUniName, $fileName, $fileExt, $fileUrl, $chunk, $chunks);

            echo json_encode(array(
                'type' => 'success',
                'message' => '上传完成',
                'data' => $thatFile->getDataArray(),
            ));
        } catch (NeedMoreDataException $e) {
            echo json_encode(array(
                'type' => 'information',
                'message' => $e->getMessage(),
            ));
        } catch (Exception $e) {
            echo json_encode(array(
                'type' => 'error',
                'message' => $e->getMessage(),
            ));
        }
    }

    /**
     * ueditor 那边移植过来的  //TODO 有bug未修复
     */
    public function ueditor_controller(){

        $CONFIG = json_decode(preg_replace("/\/\*[\s\S]+?\*\//", "", file_get_contents('application/config/ueditor_config.php')), true);
        $action = $_GET['action'];

        switch ($action) {
            case 'config':
                $result =  json_encode($CONFIG);
                break;

            /* 上传图片 */
            case 'uploadimage':
               // $result = include("action_upload.php");
               $result = $this->uploadFileAtUEditor();
                break;
            /* 抓取远程文件 */
            case 'catchimage':
                //$result = include("action_crawler.php");
                break;

            default:
                $result = json_encode(array(
                    'state'=> '请求地址出错'
                ));
                break;
        }

        /* 输出结果 */
        if (isset($_GET["callback"])) {
            if (preg_match("/^[\w_]+$/", $_GET["callback"])) {
                echo htmlspecialchars($_GET["callback"]) . '(' . $result . ')';
            } else {
                echo json_encode(array(
                    'state'=> 'callback参数不合法'
                ));
            }
        } else {
            echo $result;
        }
    }

    public function uploadFileAtUEditor()
    {
        try {
            if (!isset($_FILES["upfile"])) {
                throw new ParaException('参数非法');
            }
            $userId = $this->CurrentUser->getId();
            $thatUser = User_Model::getUserById($userId);

            //检查用户ID是否存在
            if (!$thatUser || $thatUser->getID() == 0)
                throw new NotExistException('非法用户');

            $fileUniName = $_FILES['upfile']['name'];
            $fileName = $_FILES['upfile']['name'];
            $fileExt = strtolower('.' . end(explode('.', $fileName)));
            $fileUrl = $_FILES["upfile"]["tmp_name"];
            $chunk = $this->input->post('chunk');
            $chunks = $this->input->post('chunks');

            $thatFile = YimeUpload::uploadFile($userId, $fileUniName, $fileName, $fileExt, $fileUrl, $chunk, $chunks);

            echo json_encode(array(
                "originalName" => $fileName,
                "name" => $thatFile->getName(),
                "url" => $thatFile->getAbsoluteUrl(),
                "size" => $thatFile->getSize(),
                "type" => $thatFile->getType(),
                "state" => 'SUCCESS'
            ));
        } catch (Exception $e) {
            echo json_encode(array(
                "state" => $e->getMessage()
            ));
        }
    }

    public function uploadAvatar()
    {
        try {
            $userId = $this->CurrentUser->getId();
            $thatUser = User_Model::getUserById($userId);

            //检查用户ID是否存在
            if (!$thatUser || $thatUser->getID() == 0)
                throw new NotExistException('非法用户');
            if (!isset($_FILES["file"]))
                throw new ParaException('参数非法');

            $fileUniName = strtolower($this->input->post('name'));
            $fileName = strtolower($this->input->post('file_ori_name'));
            $fileExt = strtolower('.' . end(explode('.', $fileName)));
            $fileUrl = $_FILES["file"]["tmp_name"];
            $chunk = $this->input->post('chunk');
            $chunks = $this->input->post('chunks');

            $cropParam = array(
                'crop_x1' => $this->input->post('crop_x1'),
                'crop_y1' => $this->input->post('crop_y1'),
                'crop_x2' => $this->input->post('crop_x2'),
                'crop_y2' => $this->input->post('crop_y2'),
                'crop_w' => $this->input->post('crop_w'),
                'crop_h' => $this->input->post('crop_h'),
            );

            $thatFile = YimeUpload::uploadAvatar($userId, $fileUniName, $fileName, $fileExt, $fileUrl, $chunk, $chunks, $cropParam);

            $thatUserInfo = $thatUser->getUserInfo();
            $thatUserInfo->setAvatarHash($thatFile->getHash());

            if ($thatUser->getUserInfoId()) {
                $thatUserInfo = UserInfo_Model::update($thatUserInfo);
            } else {
                $thatUserInfo = UserInfo_Model::add($thatUserInfo);
                $thatUser->setUserInfoId($thatUserInfo->getId());
                User_Model::update($thatUser);
            }

            echo json_encode(array(
                'type' => 'success',
                'message' => '修改头像成功',
                'data' => $thatFile->getDataArray(),
            ));
        } catch (NeedMoreDataException $e) {
            echo json_encode(array(
                'type' => 'information',
                'message' => $e->getMessage(),
            ));
        } catch (Exception $e) {
            echo json_encode(array(
                'type' => 'error',
                'message' => $e->getMessage(),
            ));
        }
    }

    public function getTagName()
    {
        $keyword = strtolower($this->input->get_post('q'));
        $tags = CommodityTag_Model::getAllResultArrayByKeyword($keyword);
        echo json_encode(array(
            "keywords" => $tags
        ));
    }

    //微博回调方法
    public function weibo_callback()
    {
        $weibo = SaeTOAuthV2::Init(WB_AKEY, WB_SKEY);
        if (isset($_REQUEST['code'])) {
            $keys = array();
            $keys['code'] = $_REQUEST['code'];
            $keys['redirect_uri'] = WB_CALLBACK_URL;
            try {
                $token = $weibo->getAccessToken('code', $keys);
            } catch (OAuthException $e) {
                throw new NotExistException('验证超时，请重试！');
            }
        }
        if ($token) {
            $this->session->set_userdata('token', $token);
            $this->session->set_userdata('bindType', 'weibo');
            $this->input->set_cookie('weibojs_' . $weibo->client_id, http_build_query($token));
            redirect(base_url('home/weibologin'));
        } else {
            $error_code = $this->input->get('error_code');
            redirect(base_url('home/result_show?model=error&result=' . $error_code));
        }
    }

    /**
     * @param 分享
     * type 分享方式
     * commodity_id 分享内容id
     */
    public function share()
    {
        $shareMode = $this->input->get('type');
        $commodityId = $this->input->get('commodity_id');
        $commodityrequireId = $this->input->get('commodityrequire_id');
        if($commodityId){
            $type=1;
        }else if($commodityrequireId){
            $type=2;
        }else{
            $type=0;
        }
        if ($shareMode === 'weibo') {
            WeiboManger::shareByWeibo($commodityId, $type);
        }
    }

    /**
     * @throws NotExistException
     * @internal param $ 重发邮件
     */
    public function reSendEmail()
    {
        $userId = $this->input->get_post('userId');
        $thatUser = User_Model::getUserById($userId);

        //检查用户ID是否存在
        if (!$thatUser || $thatUser->getID() == 0)
            throw new NotExistException('非法用户');

        $this->load->helper('string');
        $activationCode = random_string('alnum', 10);

        UserActivation_Model::update($this->CurrentUser->getId(), $activationCode);

        $YimeEmail = new YimeEmail;
        $sendMailResult = $YimeEmail->sendMailRegisterSuccess($this->CurrentUser->getEmail(), $activationCode);
        if ($sendMailResult) {
            preg_match_all('/(\w)+((\.\w{2,3}){1,3})$/', $this->CurrentUser->getEmail(), $mailurl);
            $mail_weburl = "http://mail." . $mailurl['0']['0'];
            if (strpos($mail_weburl, 'mail.gmail.com') !== FALSE) {
                $mail_weburl = 'http://mail.google.com'; //特判gmail
                return;
            }
            echo json_encode(array(
                'type' => 'success',
                'message' => $mail_weburl,
            ));
        } else {
            echo json_encode(array(
                'type' => 'fail',
                'message' => '邮件发送失败，请联系管理员！',
            ));
        }
    }

    public function binduser()
    {
        $bindType = $this->input->get_post('type');
        if ($bindType === 'weibo') {
            $result = WeiboManger::bindWeibo();
            if ($result) {
                echo json_encode(array(
                    'type' => 'success',
                    'message' => '绑定微博成功',
                ));
            } elseif ($result == 'addWeiboInfo_fail') {
                echo json_encode(array(
                    'type' => 'fail',
                    'message' => '获取微博信息失败，请重试！',
                ));
            } else {
                echo json_encode(array(
                    'type' => 'fail',
                    'message' => '添加微博信息失败，请重试！',
                ));
            }
        }
    }

    public function test()
    {
        header('Content-Type:text/html;charset=utf-8');
        //$CI=& get_instance();
        $this->load->library('simplehtmldom_1_5/simple_html_dom');
        $student_num = $this->input->get_post('stunum');
        $student_pwd = $this->input->get_post('stupwd');
        $check_code = $this->input->get_post('checkcode');
        $cookier = $this->session->userdata('cookie_jar');
        if (isset($cookier)) {
            StudentAuth::$cookie_jar = $this->session->userdata('cookie_jar'); //和验证码页面共享同一个cookies
        } else {
            exit();
        }
        //-----------获取登录页面
        $loginPageUrl = "http://jwxt.gdufe.edu.cn/Default2.aspx";
        $body = StudentAuth::getHtmlCurl($loginPageUrl, false, false, false);
        $content = str_get_html($body['body']);
        $hiddenInputValue = urlencode($content ->find('input[type="hidden"]', 0) ->value);
        $hiddenInputName = $content ->find('input[type="hidden"]', 0) ->name;

        //-----------执行登录操作
        $loginApiUrl = 'http://jwxt.gdufe.edu.cn/(3ir1bmampepvrb45viyulv45)/default2.aspx';
        $loginPostFields = $hiddenInputName . '=' . $hiddenInputValue . '&txtUserName=' . $student_num . '&TextBox2=' . $student_pwd . '&txtSecretCode=' . $check_code . '&RadioButtonList1=%E5%AD%A6%E7%94%9F&Button1=&lbLanguage=';
        //echo $loginPostFields;die();
        $result = StudentAuth::getHtmlCurl($loginApiUrl, $loginPostFields, 'http://jwxt.gdufe.edu.cn/(3ir1bmampepvrb45viyulv45)/default2.aspx');
        echo $result['body'];
        die();
        //----------获取学生数据
        $dataPageUrl = 'http://jwxt.gdufe.edu.cn/xsgrxx.aspx?xh=' . $student_num . '&gnmkdm=N121501';

        $HtmlDom = StudentAuth::getHtmlCurl($dataPageUrl, false, 'http://jwxt.gdufe.edu.cn/(3ir1bmampepvrb45viyulv45)/default2.aspx');
        echo $HtmlDom['body'];
        die();
        $get_body = str_get_html($HtmlDom['body']);
        $stuNum = $get_body->find('#xh', 0)->plaintext;
        $stuName = $get_body->find('#xm', 0)->plaintext;
        $stuGrade = $get_body->find('#lbl_dqszj', 0)->plaintext;
        $stuMajor = $get_body->find('#lbl_zymc', 0)->plaintext;
        echo $stuNum . '<br>' . $stuName . '<br>' . $stuGrade . '<br>' . $stuMajor;
        die();

        if (!$result) {
            throw new FormatException('认证失败，请检查填写信息是否正确');
        }

        $infoArray = explode(' ', $result);

        if (!$infoArray || !is_array($infoArray) || !$infoArray['0']) {
            throw new FormatException('认证失败，请检查填写信息是否正确');
        }
    }

    public function code()
    {
        $url=$this->input->get_post('url');
        header('Content-Type:image/jpeg;charset=UTF-8');
        $COOKIE_CODE=tempnam('./temp/', 'cookie');
        $this->session->set_userdata('cookie_jar',$COOKIE_CODE);
        $cookie_jar = $COOKIE_CODE;
        $check_code = StudentAuth::getHtmlCurl($url, false, false, false);
        echo $check_code['body'];
    }
}